import os
import re




def extract_images_from_text(text):
    # Regular expression to find markdown images
    image_pattern = r'\!\[(.*?)\]\((.*?)\)'
    images = re.findall(image_pattern, text)
    # 如果css.tgb.cn/images/face在图片url中，则剔除
    images = [(alt_text, url) for alt_text, url in images if 'css.tgb.cn/images/face' not in url]
    return images

def save_images_to_markdown(images, output_file):
    with open(output_file, 'w') as file:
        for alt_text, url in images:
            file.write(f'![{alt_text}]({url})\n')


def process_markdown_files_in_folder(folder_path, output_file):
    all_images = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.md'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    text = f.read()
                    images = extract_images_from_text(text)
                    all_images.extend(images)

    save_images_to_markdown(all_images, output_file)


if __name__ == "__main__":
    output_file = 'extracted_images.md'
    path = os.path.dirname(__file__)
    print(path)

    process_markdown_files_in_folder(path, output_file)

